package com.nsgf.library.ui.page;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;

import com.google.gson.Gson;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.LibraryInfo;
import com.zhht.htzx.databinding.ActivityNsgfWebviewBinding;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.event.RxBus;
import com.nsgf.library.utils.DialogUtil;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.widget.prckerview.TimePickerView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public class WebViewActivity extends BaseActivity {


    private StateHolder mState;

    @Override
    protected void initViewModel() {
        mState = getActivityScopeViewModel(StateHolder.class);
    }

    private ActivityNsgfWebviewBinding mBinding;

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_nsgf_webview, BR.vm, mState);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBinding = (ActivityNsgfWebviewBinding) getBinding();
        mBinding.webView.loadUrl(getIntent().getStringExtra("url"));
        mBinding.titlebar.getRoot().setVisibility(View.VISIBLE);
        mState.titleBar.set(getIntent().getStringExtra("title"));
        WebSettings mWebSettings = mBinding.webView.getWebView().getSettings();
        mWebSettings.setJavaScriptEnabled(true);//设置支持javaScript
//
//
//        //获取当前html的title 并赋值给webview_title
//        mBinding.webView.getWebView().setWebChromeClient(new WebChromeClient() {
//            @Override
//            public void onReceivedTitle(WebView view, String title) {
//                // TODO Auto-generated method stub
//                super.onReceivedTitle(view, title);
//                mBinding.titlebar.titleBarRoot.setText(title);
//                //titles.add(title);
//            }
//        });



        // 当页面加载完成后调用JavaScript方法
        mBinding.webView.getWebView().setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }
        });
        mBinding.webView.getWebView().addJavascriptInterface(new TestInterface(), "android");


    }
    /**
     * Js调用的JavascriptInterface
     */
    public class TestInterface {


        @UiThread
        @JavascriptInterface
        public void popupDate() {

            // 放在原本想更新view的地方
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

                    boolean[] type = new boolean[]{true, true, true, true, false, false};//显示类型 默认全部显示

                    new TimePickerView.Builder(WebViewActivity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            String time = ymd.format(date);
                            mBinding.webView.getWebView().evaluateJavascript("javascript:appShowTime(" + time + ");", null);
                        }
                    }).isCyclic(false)
                            .setRangDate(null, null)
                            .setType(type)
                            .setDate(Calendar.getInstance()).build().show();
                }
            });

        }

        @JavascriptInterface
        public void callNativeMethod(String src) {
//            {"path":"/monitoring/osmoticPressure","title":"渗压监测"}
            Gson gson = new Gson();
            LibraryInfo info = gson.fromJson(src, LibraryInfo.class);
            // 当用户点击链接时，不在WebView中打开，而是启动新的Activity
            Intent intent = new Intent(WebViewActivity.this, WebViewActivity.class);
            intent.putExtra("url", APIs.HTTP_H5 + info.getPath());
            intent.putExtra("title", info.getTitle());
            startActivity(intent);
        }

        @JavascriptInterface
        public void callBack() {
            finish();
            EventMsg eventMsg = new EventMsg();
            eventMsg.setMsg("webview");
            RxBus.get().post(eventMsg);

        }

    }

    /**
     * 返回键返回上一网页
     */
    @Override
    public void onBackPressed() {
        if (mBinding.webView.canGoBack()) {
            mBinding.webView.goBack();
        } else {
            finish();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
//        mBinding.webView.getWebView().loadUrl("javascript:window.location.reload(true)");

//        mBinding.webView.getWebView().reload();


        mBinding.webView.getWebView().evaluateJavascript("javascript:appShow();", null);

    }
}
